
//
//  InputBaseViewModel.m
//  RomensBI
//
//  Created by 裴飞杨 on 2017/7/14.
//
//

#import "InputBaseViewModel.h"
#import "InputBaseModel.h"

#import "InputNewTableViewController.h"

#import "RomensSDK/UIView+IndexPath.h"

#import "InputMainListView.h"
#import "InputTextViewController.h"
#import "InputCheckViewController.h"
#import "InputSearchViewController.h"
#import "InputDateTimePickerViewController.h"
#import "InputDataDetailViewController.h"
#import "InputAreasPickerViewController.h"

#import "InputWebView.h"
#import "ShowDetailView.h"

#import "InputOneLineTableViewCell.h"

#import "InputToolHelperClass.h"

#define hintOffset -250
#define hintMsgOff -200

@interface InputBaseViewModel(){
    NSIndexPath    *_inputIndexPath;       /*点击的索引*/
    InputDataModel *_dataModel;
}
//使用weak 防止循环引用 (使用strong InputERPTableViewController未能释放)
@property (nonatomic, weak) InputListBaseViewController *rootVc;
@end

@implementation InputBaseViewModel
#pragma mark - 初始化
-(instancetype)initWithRootViewController:(UIViewController*)rootVc {
    if ([super init]) {
        _rootVc = (InputListBaseViewController *)rootVc;
    }
    return self;
}
-(void)dealloc{
}
#pragma mark - 点击编辑
-(void)editInput {
    self.dataModel.editInput = true;
    
    NSArray *models = self.dataModel.templates;
    for ( int i = 0; i < models.count; i ++) {
        InputSectionModel *sectionModel = models[i];
        [[self.dataModel mutableArrayValueForKeyPath:ObserverKey] replaceObjectAtIndex:i withObject:sectionModel];
    }
}
#pragma mark - 获取点击对象
//获取sectionModel
-(InputSectionModel *)didSelectSectionModel:(NSIndexPath *)index {
    if (!index) {
        return nil;
    }
    return self.dataModel.templates[index.section];
}
//获取cellModel
-(InputCellModel *)didSelectCellModel:(NSIndexPath *)index {
    InputSectionModel *section = [self didSelectSectionModel:index];
    if (!section) {
        return nil;
    }
    return  section.nodes[index.row];
}

#pragma mark - 跳转View
-(void)pushInputViewWithIndexPath:(NSIndexPath *)indexpath {
    //点击索引
    _inputIndexPath = indexpath;
    //获取使用的model
    InputSectionModel *sectionModel  = [self didSelectSectionModel:indexpath];
    __block InputCellModel *cellModel = [self didSelectCellModel:indexpath];
    
    if (!self.dataModel.editInput || !cellModel || cellModel.isLock) {
        return;
    }
    NSString *inputType = cellModel.inputtype;
    InputBaseViewController *baseViewController;
    __weak typeof(self)wSelf = self;
    if ([inputType isEqualToString:TEXT_MULTI_TYPE] || [inputType isEqualToString:TEXT_TYPE] || [inputType isEqualToString:INT_TYPE] || [inputType isEqualToString:DECIMAL_TYPE]) {
        //输入页
        InputTextViewController *inputTextVc = [[InputTextViewController alloc] init];
        inputTextVc.inputDoneBlock = ^(id inputDone) {
            cellModel.inputDetail = (NSString *)inputDone;
            [wSelf reloadListDataArray];
        };
        baseViewController = inputTextVc;
        
    } else if ([inputType isEqualToString:MLOOKUP_TYPE] || [inputType isEqualToString:LOOKUP_TYPE]) {
        //单选、多选
        InputCheckViewController *checkVc = [[InputCheckViewController alloc] init];
        checkVc.inputDoneBlock = ^(id inputDone) {
            NSArray *array = [wSelf lookupAction:cellModel];
            cellModel.inputDetail  = array[0];
            cellModel.combinDetail = array[1];
            [wSelf reloadListDataArray];
        };
        baseViewController = checkVc;
        
    } else if ([inputType isEqualToString:PICKDATE_TYPE] || [inputType isEqualToString:DATETIME_TYPE]) {
        //日期、日期时间选择
        InputDateTimePickerViewController *pickVc = [[InputDateTimePickerViewController alloc] init];
        pickVc.inputDoneBlock = ^(id inputDone) {
            cellModel.inputDetail = (NSString *)inputDone;
            [wSelf reloadListDataArray];
        };
        baseViewController = pickVc;
        
    } else if ([inputType isEqualToString:DATASOURCE_TYPE]) {
        //数据选择（搜索、单选）
        if (isEmptyString(_rootVc.defaultUrl)) {
            [_rootVc showHint:@"不可编辑，原因：DATA_SOURCE缺失相关配置" yOffset:HINTOFF];
            NSLog(@"请设置默认URL，如：http://im.yiyao365.cn/yyzs/index.php");
            return;
        }
        //筛选
        InputSearchViewController *searchVc = [[InputSearchViewController alloc] init];
        searchVc.requestUrlStr = [_rootVc.defaultUrl stringByAppendingString:cellModel.sourceHandle];
        searchVc.queryType = cellModel.sourceQueryType;
        
        //拼接参数(reference关联项)
        for (NSString *key in cellModel.reference) {
            searchVc.parames[key] = [InputToolHelperClass selectNodeInputValue:key byTemplate:sectionModel];
        }
        searchVc.selectBlock = ^(NSDictionary *dict) {
            //刷新callBack项
            for (NSString *reloadKey in cellModel.sourceCallBack) {
                [InputToolHelperClass setupNodeInputValue:reloadKey nodeValue:dict[reloadKey] byTemplate:sectionModel];
            }
            [wSelf reloadListDataArray];
        };
        baseViewController = searchVc;
        
    } else if ([inputType isEqualToString:DATADETAIL_TYPE]) {
        //数据集列表，可添加
        NSString *handleName = cellModel.sourceHandle;
        NSString *queryType = cellModel.sourceQueryType;
        NSArray *parames = cellModel.parames;
        if (isEmptyString(_rootVc.defaultUrl) || isEmptyString(handleName) || isEmptyString(queryType) || parames.count == 0) {
            [_rootVc showHint:@"不可编辑，原因：DATA_SELECT缺失相关配置" yOffset:HINTOFF];
            return;
        }
        InputDataDetailViewController *dataDetailVc = [[InputDataDetailViewController alloc] init];
        dataDetailVc.templateCode = cellModel.templateCode;
        dataDetailVc.mainKey = [InputToolHelperClass selectNodeInputValue:cellModel.mainKey byTemplate:sectionModel];
        dataDetailVc.requestUrl = _rootVc.defaultUrl;
        dataDetailVc.requestHandler = handleName;
        dataDetailVc.requestQueryType = queryType;
        for (NSString *parameKey in parames) {
            [dataDetailVc.requestParames setValue:[InputToolHelperClass selectNodeInputValue:parameKey byTemplate:sectionModel] forKey:parameKey];
        }
        dataDetailVc.inputDoneBlock = ^(id inputDone) {
            cellModel.inputDetail = (NSString *)inputDone;
            [wSelf reloadListDataArray];
        };
        baseViewController = dataDetailVc;
    } else if ([inputType isEqualToString: REGION_TYPE]) {
        //省市区选择
        InputAreasPickerViewController *pickVc = [[InputAreasPickerViewController alloc] init];
        pickVc.inputDoneBlock = ^(id inputDone) {
            cellModel.inputDetail = (NSString *)inputDone;
            [wSelf reloadListDataArray];
        };
        baseViewController = pickVc;
    }
    baseViewController.model = cellModel;
    _rootVc.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    [_rootVc.navigationController pushViewController:baseViewController animated:YES];
}

#pragma mark - Lookup Action(单选、多选)
-(NSArray *)lookupAction:(InputCellModel *)cellModel {
    NSString *inputDetail  = @"";
    NSString *combinDetail = @"";
    for (ActionSheetContentModel *temp in cellModel.items) {
        if (temp.isCheck) {
            if (isEmptyString(inputDetail)) {
                inputDetail  = [inputDetail stringByAppendingFormat:@"%@",temp.contentTitle];
                combinDetail = [combinDetail stringByAppendingFormat:@"%@",temp.contentValue];
            } else {
                inputDetail  = [inputDetail stringByAppendingFormat:@",%@",temp.contentTitle];
                combinDetail = [combinDetail stringByAppendingFormat:@",%@",temp.contentValue];
            }
        }
    }
    return [NSArray arrayWithObjects:inputDetail, combinDetail, nil];
}

#pragma mark - UISwitch Action (Bool)
-(void)switchAction:(id)sender {
    UISwitch *switchBtn = (UISwitch *)sender;
    _inputIndexPath = switchBtn.c_NSIndexPath;
    InputCellModel *cellModel = [self didSelectCellModel:_inputIndexPath];
    if (!cellModel || cellModel.isLock) {
        return;
    }
    if ([switchBtn isOn]) {
        cellModel.inputDetail = @"1";
    } else {
        cellModel.inputDetail = @"0";
    }
    _inputIndexPath = nil;
}
#pragma mark - 判断必选项
-(BOOL)isMustInput {
    //如果是不可编辑的，返回NO
    if (!self.dataModel.editInput) {
        return NO;
    }
    for (InputSectionModel *sectionModel in self.dataModel.templates) {
        for (InputCellModel *cellModel in sectionModel.nodes) {
            if (!cellModel.isLock && cellModel.isMustInput && !cellModel.ishidden) {
                NSString *detailStr = [InputToolHelperClass selectNodeInputValue:cellModel];
                if (isEmptyString(detailStr)) {
                    [_rootVc showHint:[NSString stringWithFormat:@"%@为必填项，不能为空！", cellModel.nameCaption]];
                    return YES;
                }
            }
        }
    }
    return NO;
}

#pragma mark - 更新数组
-(void)reloadListDataArray {
    InputSectionModel *sectionModel = [self didSelectSectionModel:_inputIndexPath];
    if (!sectionModel) {
        return;
    }
    [[self.dataModel mutableArrayValueForKeyPath:ObserverKey] replaceObjectAtIndex:_inputIndexPath.section withObject:sectionModel];
}
#pragma mark - 跳转新的输入ViewController
-(void)pushNewInputViewControllerWithSection:(NSInteger)section {
    InputSectionModel *sectionModel = self.dataModel.templates[section];
    InputNewTableViewController *newInputVc = [[InputNewTableViewController alloc] init];
    newInputVc.title = sectionModel.nameCaption;
    newInputVc.sectionModel = sectionModel;
    _rootVc.navigationItem.backBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    [_rootVc.navigationController pushViewController:newInputVc animated:YES];
}

#pragma mark - 双击展示
-(void)showDetailVauleWithCell:(UITableViewCell *)cell {
    NSString *title = @"";
    NSString *value = @"";
    if ([cell isKindOfClass:[InputMultiLineTableViewCell class]]) {
        title = ((InputOneLineTableViewCell *)cell).titleLabel.text;
        value = ((InputOneLineTableViewCell *)cell).valueLabel.text;
    }
    if (isEmptyString(title) || isEmptyString(value)) {
        return;
    }
    if (self.showDetailViewBlock) {
        self.showDetailViewBlock(title, value);
    }
}
@end
